# -*- encoding:utf-8 -*-
# @time:2023-05-21 0:26
# @Author : serein
# @Email: serein@qq.com
# @File:serializers.py
# @Software: PyCharm

from rest_framework import serializers
from rest_framework.fields import SerializerMethodField

from cart.models import Cart
from shopping.serializers import CommoditySerializer


class CartSerializers(serializers.ModelSerializer):
    #自定义返回字段
    commodityDetail = SerializerMethodField()
    class Meta:
        model = Cart
        exclude = ['is_delete']
    def validate(self, data):
        if data['number']<=0:
            raise serializers.ValidationError('购买商品的数量出现错误')
        elif data['number']>data['commodity'].stock:
            raise serializers.ValidationError('购买商品的数量超出库存值')
        else:
            return data
    def get_commodityDetail(self,cart):
        return CommoditySerializer(cart.commodity).data
